package encrpcclient

import (
	"context"

	"gitee.com/fhe-search/fhe-search-rpc/encrpc"
	"google.golang.org/grpc"
)

var (
	pConnect *grpc.ClientConn
	pClient  encrpc.EncServiceClient
)

func NewClient(target string) {
	conn, err := grpc.NewClient(target, grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	pConnect = conn
	pClient = encrpc.NewEncServiceClient(conn)
}

func CloseClient() {
	pConnect.Close()
}

func SymEncUtf8(utf8ClearText string) ([]byte, error) {
	req := &encrpc.SymEncUtf8Request{
		Utf8ClearText: utf8ClearText,
	}
	resp, err := pClient.SymEncUtf8(context.Background(), req)
	if err != nil {
		return nil, err
	} else {
		return resp.EncryptedData, nil
	}
}

func SymDecUtf8(utf8EncText []byte) (string, error) {
	req := &encrpc.SymDecUtf8Request{
		Utf8EncText: utf8EncText,
	}
	resp, err := pClient.SymDecUtf8(context.Background(), req)
	if err != nil {
		return "", err
	} else {
		return resp.DecryptedData, nil
	}
}

func SymEncS32Ex(int32Arr []int32) ([][]byte, error) {
	req := &encrpc.SymEncS32ExRequest{
		Int32Arr: int32Arr,
	}
	resp, err := pClient.SymEncS32Ex(context.Background(), req)
	if err != nil {
		return nil, err
	} else {
		return resp.EncryptedData, nil
	}
}

func SymEncS32(plain int32) ([]byte, error) {
	req := &encrpc.SymEncS32Request{
		Plain: plain,
	}
	resp, err := pClient.SymEncS32(context.Background(), req)
	if err != nil {
		return nil, err
	} else {
		return resp.EncryptedData, nil
	}
}

func SymDecS32(encData []byte) (int32, error) {
	req := &encrpc.SymDecS32Request{
		EncData: encData,
	}
	resp, err := pClient.SymDecS32(context.Background(), req)
	if err != nil {
		return 0, err
	} else {
		return resp.DecryptedData, nil
	}
}

func FheEncUtf8(utf8Text string) ([]byte, error) {
	req := &encrpc.FheEncUtf8Request{
		Utf8Text: utf8Text,
	}
	resp, err := pClient.FheEncUtf8(context.Background(), req)
	if err != nil {
		return nil, err
	} else {
		return resp.EncryptedData, nil
	}
}

func FheDecUtf8(utf8EncText []byte) (string, error) {
	req := &encrpc.FheDecUtf8Request{
		Utf8EncText: utf8EncText,
	}
	resp, err := pClient.FheDecUtf8(context.Background(), req)
	if err != nil {
		return "", err
	} else {
		return resp.DecryptedData, nil
	}
}

func FheSub(enc1, enc2 []byte) (diff []byte, err error) {
	req := &encrpc.FheSubRequest{
		Enc1: enc1,
		Enc2: enc2,
	}
	resp, err := pClient.FheSub(context.Background(), req)
	if err != nil {
		return nil, err
	} else {
		return resp.Diff, nil
	}
}

func FheDecDiff(diff []byte) (bool, error) {
	req := &encrpc.FheDecDiffRequest{
		Diff: diff,
	}
	resp, err := pClient.FheDecDiff(context.Background(), req)
	if err != nil {
		return false, err
	} else {
		return resp.Result, nil
	}
}

func GetBucket8(term string) int {
	req := &encrpc.GetBucket8Request{
		Term: term,
	}
	resp, err := pClient.GetBucket8(context.Background(), req)
	if err != nil {
		return -1
	} else {
		return int(resp.Bucket8)
	}
}
